var dtree;
var $;
var table;
var layer;
layui.extend({
    dtree:'../layui/layui_ext/dtree/dtree'
}).use(['dtree','table','element','layer'],function(){
    dtree=layui.dtree;
    $=layui.jquery;
    table=layui.table;
    layer=layui.layer;

    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象

    //ztree
    setDtree();
    function setDtree(){
        $.ajax({
            url:"/SyteacherSelController/ActicleTree",
            type:"post",
            dataType:"json",
            data:[],
            success:function(data){
                DtreeView(data.data);
            }
        })
    }
    function DtreeView(data){


        $(function(){
            //点击节点获取值
            function zTreeOnClick(event, treeId, treeNode) {
                seTab(treeNode.id,'','','','')
                return false;
            };

            var ZtreeTile;
            function OnRightClick(event, treeId, treeNode) {
                if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                    zTree.cancelSelectedNode();
                    showRMenu("root", event.clientX, event.clientY);
                } else if (treeNode && !treeNode.noR) {
                    ZtreeTile=treeNode;
                    showRMenu("node", event.clientX, event.clientY);
                }
            }

            function showRMenu(type, x, y) {
                $("#rMenu ul").show();
                if (type=="root") {
                    $("#m_del").hide();
                    $("#m_check").hide();
                    $("#m_unCheck").hide();
                } else {
                    $("#m_del").show();
                    $("#m_check").show();
                    $("#m_unCheck").show();
                }

                y += document.body.scrollTop;
                x += document.body.scrollLeft;
                rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

                $("body").bind("mousedown", onBodyMouseDown);
            }
            function hideRMenu() {
                if (rMenu) rMenu.css({"visibility": "hidden"});
                $("body").unbind("mousedown", onBodyMouseDown);
            }
            function onBodyMouseDown(event){
                if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                    rMenu.css({"visibility" : "hidden"});
                }
            }

            //添加节点
           $("#m_add").on("click",function() {
                hideRMenu();
               //绑定添加事件，并定义添加操作
                   var parentId=ZtreeTile.id;
                   layer.open({
                       type:1,
                       title:"添加节点",
                       area:['400px','200px'],
                       shade:0.4,
                       offset:'auto',
                       content:"<div class='layui-inline' style='margin:40px 0px 0px 40px;z-index: 10'>" +
                           "<label class='layui-form-label'>分类名称：</label>" +
                           "<div class='layui-input-block'>" +
                           "<input type='text' name='name' id='treeNode_id' class='layui-input' placeholder='课程分类'/>" +
                           "</div>" +
                           "</div>",
                       btn:['添加','取消'],
                       yes:function(){
                           var name=$("#treeNode_id").val();
                           if(name===""||name===null||name===undefined) {
                               layer.msg("分类不能为空", {icon: 5});
                           }else{
                               $.ajax({
                                   url:"/SyteacherSelController/addActTree",
                                   type:"post",
                                   dataType:"json",
                                   data:{"parentId":parentId,"name":name,"createUser":create.user_id},
                                   success:function(dat){
                                       location.reload(true);
                                   }
                               });
                           }
                       }
                   });
            });
            //修改节点
            $("#m_check").on("click",function(){
                layer.open({
                    type:1,
                    title:"修改节点",
                    area:['400px','200px'],
                    shade:0.4,
                    offset:'auto',
                    content:"<div class='layui-inline' style='margin:40px 0px 0px 40px;z-index: 10'>" +
                        "<label class='layui-form-label'>分类名称：</label>" +
                        "<div class='layui-input-block'>" +
                        "<input type='text' name='name' id='treeNode_id' class='layui-input' placeholder='课程分类'/>" +
                        "</div>" +
                        "</div>",
                    btn:['修改','取消'],
                    yes:function(){
                        var name=$("#treeNode_id").val();
                        var id = ZtreeTile.id

                        if(name===""||name===null||name===undefined) {
                            layer.msg("分类不能为空", {icon: 5});
                        }else{
                            $.ajax({
                                url:"/SyteacherSelController/upActTree",
                                type:"post",
                                dataType:"json",
                                data:{"id":id,"Newname":name,"updateUser":create.user_id},
                                success:function(data){
                                    location.reload(true);
                                }
                            });
                        }

                    }

                });
                hideRMenu();
            });
            //删除节点
            $("#m_del").on("click",function() {
                hideRMenu();
                $.ajax({
                    url:"/SyteacherSelController/delActTree",
                    type:"post",
                    dataType:"json",
                    data:{"acticleCategoryId":ZtreeTile.id},
                    success:function(data){
                        location.reload();
                    }
                })
            });
            function resetTree() {
                hideRMenu();
                $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
            }

            var zTree, rMenu;
            $(document).ready(function(){
                $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
                zTree = $.fn.zTree.getZTreeObj("treeDemo");
                rMenu = $("#rMenu");
            });


            var setting={
                callback: {
                    onRightClick: OnRightClick,
                    onClick: zTreeOnClick,
                },
                view: {
                    dblClickExpand: false,
                    showIcon: false,

                }
            };
            var zTreeNodes=data;
            var city = $.fn.zTree.init($("#tree"), setting, zTreeNodes);
        });


    }

    /*模糊查询*/

    $("#btn_2").on('click',function(){
        var title=$("#actId").val();
        var name=$("#userId").val();
        var acc=$("#accId").val();

        var createDate=$("#createDate").val();
        var articleLike=$("#articleLike").val();
        var collectionNum=$("#collectionNum").val();
        var articleHits=$("#articleHits").val();
        var articleShare=$("#articleShare").val();
        seTab(0,title,name,acc,createDate,articleLike,collectionNum,articleHits,articleShare);
    });


    seTab("","","","","","","","","");
    /* 查询表结构开始*/
    function seTab(id,title,name,acc, createDate,articleLike,collectionNum,articleHits,articleShare){
        $.ajax({
            url:"/SyteacherSelController/ForumTab",
            type:"post",
            dataType:"json",
            data:{"actid":id,"title":title,"name":name,"acc":acc,  "createDate":createDate,"articleLike":articleLike,"collectionNum":collectionNum,"articleHits":articleHits,"articleShare":articleShare},
            success:function(data){
                TabView(data.data);
            }
        })
    }
    /*查询表结构结束*/
    /*日期转换*/
    function settime(da){
        var date=new Date(da);
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hours=date.getHours();
        var mm=date.getMinutes();
        var s=date.getSeconds();
        return year+'-'+add(month)+'-'+add(day)+' '+add(hours)+':'+add(mm)+':'+add(s);
        //return year+'-'+month+'-'+day+' '+hours+':'+mm+':'+s;
    };
    function add(time){//给非整数添0
        return time<10?'0'+time:time;
    };

    /*渲染表开始*/
    function TabView(da){

            table.render({
            elem:"#tab_id",
            data:da,
            limit:5,
            toolbar:'#toolbarDemo',
            page:{
                layout:['count','prev','page','next','limit','skip','refresh'],
                limits:[3,6,9],
                first:"首页",
                last:"尾页",
            },
            cols:[[
                {title:'序号',width:70,align:'center',templet:function(data){
                        return data.LAY_INDEX;
                 }},
                {field:'username',title:'用户昵称',align:'center'},
                {field:'articleTitle',title:'文章标题',align:'center'},
                {field:'url',title:'微圈图片',align: 'center',templet:function(data){
                        if(data.articleUrl!=null){
                            return "<img src='"+data.articleUrl+"'height='100'>";
                        }else{
                            return "<span>无图片</span>";
                        }

                 }},
                {field:'createDate',title:'创建日期',align:'center',templet:function(data){
                       var time= settime(data.createDate);
                       return time;
                    }},
                {field:'useraccount',title:'用户账号',align:'center'},
                {field:'articleLike',title:'点赞数量',align:'center'},
                {field:'articleHits',title:'点击数量',align:'center'},
                {field:'articleReviews',title:'评论数量',align:'center'},
                {field:'articleShare',title:'分享数量',align:'center'},
                {field:'details',title:"操作",align:'center',templet:function(data){
                        return "<a id='a_id' href='#' onclick='javascript:selectTable(\""+data.microcircleId+"\")'>查看</a><a id='a_id'  class='a_cl' href='#' onclick='delectTable(\""+data.microcircleId+"\")'>删除</a>"
                 }}

            ]]
        })
    }
    /*渲染表结束*/
})



/*查看详情*/
function selectTable(id){
    var index = layer.open({
        type:2,
        title:"课程详情",
        area:['800px','600px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"/operation/comment/TeaEssayView.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('input[name=courseId]').val(id);
        }
    });
    layer.full(index);
}
/*删除课程*/
function delectTable(id){
    layer.msg("确定删除此课程？", {
        time: 20000, //20s后自动关闭
        btn: ['确定', '取消'],
        yes: function(index, layero){
            $.ajax({
                url:"/SyteacherSelController/delectForum",
                type:"post",
                dataType:"json",
                data:{"microcircleId":id},
                success:function(data){
                    location.reload(true);
                }
            });
            window.parent.location.reload();
        },
        btn2:function(index, layero){
            window.parent.location.reload();
        }
    })

}

//高级检索
function retrieval() {
    //点击检索之后清空输入框
    $("input[name!='userId']").val('');
    $(this).find("option:selected").removeAttr("selected");

    layer.open({
        type : 2,
        id:1,
        title : "<div style='color:#666666;font-weight: 600;background: #F8F8F8;'>高级检索</div>",
        area : [ '670px', '500px' ],
        maxmin: true,
        shade : 0,
        offset: 'auto',
        content :"/teacher/AdministrationForumRetrieval.html",
        success:function(){

        }
    });
    window.layer_1=layer;
}

//页面刷新
function refresh(){
    location.reload(true);
}
